package com.android.manghe.coupon.fragment

import android.content.Intent
import android.graphics.drawable.BitmapDrawable
import android.net.Uri
import android.os.Bundle
import android.text.Editable
import android.text.TextUtils
import android.text.TextWatcher
import android.view.Gravity
import android.view.View
import android.view.WindowManager
import android.view.animation.Animation
import android.view.animation.TranslateAnimation
import android.widget.PopupWindow
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.android.base.frame.extend.IRefresh
import com.android.base.frame.title.ETitleType
import com.android.base.frame.view.MVPFragment
import com.android.base.tools.BigDecimalUtils
import com.android.base.tools.Glide.GlideHelper
import com.android.base.tools.ToastUtil
import com.android.base.view.recycler.RecyclerViewDivider
import com.android.base.view.recycler.listener.OnItemClickListener
import com.android.manghe.R
import com.android.manghe.cache.StatusHolder
import com.android.manghe.cache.UserHolder
import com.android.manghe.common.activity.PaySuccessActivity
import com.android.manghe.common.model.PaymentTypeRes
import com.android.manghe.common.webview.ERefreshWebType
import com.android.manghe.common.webview.SimpleWebViewActivity
import com.android.manghe.common.webview.WebViewActivity
import com.android.manghe.common.webview.WebViewParameter
import com.android.manghe.coupon.adapter.CouponAdapter
import com.android.manghe.coupon.adapter.PaymentAdapter
import com.android.manghe.coupon.model.CouponRes
import com.android.manghe.coupon.presenter.PCoupon
import com.android.manghe.user.activity.LoginActivity
import com.android.manghe.view.dialog.ConfirmPayResultDialog
import com.android.manghe.view.dialog.InputCouponMoneyDialog
import com.scwang.smartrefresh.layout.SmartRefreshLayout
import kotlinx.android.synthetic.main.fragment_coupon.*
import java.util.*

class CouponFragment : MVPFragment<PCoupon>(), IRefresh {

    private var mAdapter: CouponAdapter? = null
    private var mPaymentAdapter: PaymentAdapter? = null
    private var mCouponId = ""
    private var mPayId = ""
    private var mCurrentAccount = 1
    public var mCurrentPrice: Double = 0.00
    private var mCurrentCoin = 0

    override fun getLayoutId() = R.layout.fragment_coupon
    override fun showToolBarType() = ETitleType.NO_TITLE
    override fun initData(savedInstanceState: Bundle?, parent: View) {
        initListView()
        initListener()
        showLoadingDialog()
        p.getBanner()
        p.getCoupon()
        p.getCouponInputConfig()
    }

    fun showInput(isShow: Boolean) {
        layoutInput.visibility = if (isShow) View.VISIBLE else View.GONE
    }

    private fun initListener() {
        etInputMoney.setOnClickListener(object : View.OnClickListener {
            override fun onClick(v: View?) {
                //弹出金额输入框
                mAdapter?.selectedItem(null)
                layoutBarAmount.visibility = View.GONE
                etInputMoney.setText("")
                mCurrentAccount = 0
                dealPriceCoin()
                val dialog = InputCouponMoneyDialog(
                    activity!!,
                    object : InputCouponMoneyDialog.IInputListener {
                        override fun confirm(num: Int) {
                            etInputMoney.setText(num.toString())
                        }
                    })
                dialog.show()
                etInputMoney.setBackgroundResource(R.drawable.edit_text_focus_shape)
            }
        })
        etInputMoney.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    if (!TextUtils.isEmpty(etInputMoney.text.toString())) {
                        mCurrentAccount = etInputMoney.text.toString().toInt()
                        dealPriceCoin()
                    }
                } catch (e: java.lang.Exception) {
                }
            }

        })

        tvReduce.setOnClickListener {
            if (mCurrentAccount > 1) {
                mCurrentAccount--
                tvAccount.text = mCurrentAccount.toString()
                dealPriceCoin()
            }
        }
        tvAdd.setOnClickListener {
            if (mCurrentAccount < 1000) {
                mCurrentAccount++
                dealPriceCoin()
            }
        }
        viewNoCoupon.setOnClickListener {
            showLoadingDialog()
            p.getCoupon()
        }
        mAdapter?.setOnItemClickListener(object :
            OnItemClickListener<CouponRes.DataBean.CouponInfo> {
            override fun onClick(view: View?, item: CouponRes.DataBean.CouponInfo?) {
                etInputMoney.setText("")
                etInputMoney.setBackgroundResource(R.drawable.edit_text_unfocus_shape)
                mCurrentAccount = 1
                mAdapter?.selectedItem(item)
                layoutBarAmount.visibility = View.VISIBLE
                dealPriceCoin()
            }
        })

        btnPay.setOnClickListener {
            val userInfo = UserHolder.getUserInfo(activity)
            if (null == userInfo) {
                open(LoginActivity::class.java)
            } else {
                if (layoutBarAmount.visibility == View.GONE) {
                    if (TextUtils.isEmpty(etInputMoney.text.toString())) {
                        ToastUtil.showShort(activity, "请输入金额")
                        return@setOnClickListener
                    }
                    if (!TextUtils.isEmpty(etInputMoney.text.toString())
                        && etInputMoney.text.toString().toInt() < 5
                    ) {
                        ToastUtil.showShort(activity, "最少充值5元")
                        return@setOnClickListener
                    }
                }
                p.getPaymentType()
            }
        }
    }

    private fun dealPriceCoin() {
        try {
            if (layoutBarAmount.visibility == View.VISIBLE) {
                tvAccount.text = mCurrentAccount.toString()
                val coupon = mAdapter?.selectedCoupon
                mCouponId = coupon!!.id
                mPayId = coupon!!.id
                val singlePrice = coupon?.price
                val singleCoin = coupon?.coin?.toInt()
                singlePrice?.let {
                    mCurrentPrice =
                        BigDecimalUtils.mul(it, mCurrentAccount.toString(), 2).toDouble()
                    tvPrice.text = mCurrentPrice.toString()
                }
                singleCoin?.let {
                    mCurrentCoin = it * mCurrentAccount
                }
            } else {
                mCouponId = p.inputConfig.id
                mPayId = p.inputConfig.id
                val singlePrice = p.inputConfig?.price
                val singleCoin = p.inputConfig?.coin?.toInt()
                singlePrice?.let {
                    mCurrentPrice =
                        BigDecimalUtils.mul(it, mCurrentAccount.toString(), 2).toDouble()
                    tvPrice.text = mCurrentPrice.toString()
                }
                singleCoin?.let {
                    mCurrentCoin = it * mCurrentAccount
                }

            }
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

    private fun initListView() {
        try {
            recyclerView.layoutManager =
                LinearLayoutManager(
                    activity!!,
                    LinearLayoutManager.VERTICAL,
                    false
                )
            mAdapter = CouponAdapter(activity, ArrayList<CouponRes.DataBean.CouponInfo>())
            recyclerView.adapter = mAdapter
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    fun updateData(couponList: List<CouponRes.DataBean.CouponInfo>) {
        mAdapter?.let {
            recyclerView.visibility = View.VISIBLE
            layoutBottomBar.visibility = View.VISIBLE
            viewNoCoupon.visibility = View.GONE
            it.update(couponList)
            mCurrentAccount = 1
            dealPriceCoin()
        }
    }


    private var payPopupWindow: PopupWindow? = null
    private var payPopupView: View? = null
    private var payAnimation: TranslateAnimation? = null
    fun showPayPop(paymentList: List<PaymentTypeRes.DataBean.PaymentBean>) {
        if (payPopupWindow == null) {
            payPopupView = View.inflate(activity, R.layout.popup_pay_coupon, null)
            payPopupWindow = PopupWindow(
                payPopupView,
                WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.WRAP_CONTENT
            )
            // 设置背景图片， 必须设置，不然动画没作用
            payPopupWindow!!.setBackgroundDrawable(BitmapDrawable())
            payPopupWindow!!.isFocusable = true
            // 设置点击popupwindow外屏幕其它地方消失
            payPopupWindow!!.isOutsideTouchable = true
            // 平移动画相对于手机屏幕的底部开始，X轴不变，Y轴从1变0
            payAnimation = TranslateAnimation(
                Animation.RELATIVE_TO_PARENT, 0f, Animation.RELATIVE_TO_PARENT, 0f,
                Animation.RELATIVE_TO_PARENT, 1f, Animation.RELATIVE_TO_PARENT, 0f
            )
            payAnimation!!.duration = 100
            payPopupWindow!!.setOnDismissListener {
                zheZhao.visibility = View.GONE
            }
            val payRecyclerView = payPopupView!!.findViewById<RecyclerView>(R.id.payRecyclerView)
            payRecyclerView.layoutManager =
                LinearLayoutManager(
                    activity!!,
                    LinearLayoutManager.VERTICAL,
                    false
                )
            mPaymentAdapter = PaymentAdapter(activity, paymentList)
            payRecyclerView.addItemDecoration(
                RecyclerViewDivider(
                    activity,
                    LinearLayoutManager.HORIZONTAL
                )
            )
            payRecyclerView.adapter = mPaymentAdapter
            mPaymentAdapter?.setOnItemClickListener { adapter, view, position ->
                mPaymentAdapter?.selectedItem(adapter.data[position] as PaymentTypeRes.DataBean.PaymentBean)
            }

            payPopupView!!.findViewById<TextView>(R.id.tvToPay).setOnClickListener {
                //支付
                try {
                    payPopupWindow?.dismiss()
                    showLoadingDialog()
                    p.getOrderMsg(
                        mCouponId,
                        mCurrentAccount.toString(),
                        mPaymentAdapter?.selectedPayment?.pay_id,
                        mPaymentAdapter?.selectedPayment?.pay_code
                    )
                } catch (e: Exception) {
                    e.printStackTrace()
                }
            }
            payPopupView!!.findViewById<TextView>(R.id.tvCancel).setOnClickListener {
                //支付
                payPopupWindow?.dismiss()
            }

        }
        mPaymentAdapter?.let {
            it.update(paymentList)
        }
        // 设置popupWindow的显示位置，此处是在手机屏幕底部且水平居中的位置
        payPopupWindow!!.showAtLocation(
            activity!!.findViewById(R.id.tabLayout),
            Gravity.BOTTOM,
            0,
            0
        )
        payPopupView!!.startAnimation(payAnimation)
        zheZhao.visibility = View.VISIBLE
    }

    fun noData() {
        recyclerView?.visibility = View.GONE
        layoutBottomBar?.visibility = View.GONE
        viewNoCoupon?.visibility = View.VISIBLE
    }

    override fun getRefreshView(): SmartRefreshLayout {
        return mView.findViewById(R.id.refreshLayout)
    }

    override fun onRefresh() {
        p.getCoupon()
    }

    override fun onLoad() {

    }

    fun payFail() {
        ToastUtil.showShort(activity, "未完成支付")
    }

    fun paySuccess() {
        open(PaySuccessActivity::class.java)
    }

    fun showBanner(picUrl: String, href: String) {
        if (TextUtils.isEmpty(picUrl)) {
            ivTopBanner.setBackgroundResource(R.mipmap.banner)
        } else {
            GlideHelper.load(activity, picUrl, ivTopBanner)
        }
        if (!TextUtils.isEmpty(href)) {
            ivTopBanner.setOnClickListener {
                WebViewActivity.showActivity(
                    mContext, WebViewParameter.WebParameterBuilder()
                        .setUrl(href)
                        .setShowProgress(true)
                        .setCanHistoryGoBackOrForward(true)
                        .setReloadable(true)
                        .setReloadType(ERefreshWebType.ClickRefresh)
                        .setCustomTitle(mContext.getString(R.string.app_name))
                        .build()
                )
            }
        } else {
            ivTopBanner.setOnClickListener(null)
        }
    }

    fun toPayByH5(url: String) {
        StatusHolder.mCurrentVoucherPrice = mCurrentPrice
        SimpleWebViewActivity.showActivity(activity!!, url, "支付")
    }

    fun toPayByBrowser(url: String, orderId: String) {
        StatusHolder.mCurrentVoucherPrice = mCurrentPrice
        val uri: Uri = Uri.parse(url)
        val intent = Intent(Intent.ACTION_VIEW, uri)
        startActivity(intent)
        //弹出让用户确定是否支付成功的弹出框
        orderId?.let {
            val dialog = ConfirmPayResultDialog(activity!!, orderId, object : ConfirmPayResultDialog.CallBack{
                override fun callBack(orderId: String) {
                    p.checkOrderStatus(orderId)
                }
            })
            dialog.show()
        }
    }

}
